//
//  UIDevFormTableView.swift
//  DevFormView
//  表单
//  Created by dev on 15/9/16.
//  Copyright (c) 2015年 devilved. All rights reserved.
//

import UIKit

class UIDevFormTableView: UITableView, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate, UITextViewDelegate {

    var sections:[DevFormSection] = []
    
    var lastFootHeight:CGFloat = 0.01
    
    var onReturnKeyClick:(UIDevFormTableView, DevFormField, UIReturnKeyType) -> Void = {(formTableView:UIDevFormTableView, formField DevFormField, returnKeyType:UIReturnKeyType) -> Void in}
    
    override func awakeFromNib() {
        super.awakeFromNib()
        self.initUIDevFormTableView()
    }
    
    func initUIDevFormTableView() {
        if #available(iOS 8.0, *) {
            self.layoutMargins = UIEdgeInsetsZero
        }
        self.initDelegate()
//        self.initTapGestureRecognizer()
        self.initRegisterFormFieldCells()
        self.initNotification()
    }
    
    func initDelegate() {
        self.dataSource = self
        self.delegate = self
    }
    
    func initRegisterFormFieldCells() {
        self.registerClass(UIDevFormTableViewCell.self, forCellReuseIdentifier: "UIDevFormTableViewCellIdentifier")
    }
    
    func initNotification() {
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "onKeyBoardWillShow:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "onKeyBoardWillHide:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
//    func initTapGestureRecognizer() {
//        let tap:UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "onFormTableViewTouch")
//        tap.delegate = self
//        self.addGestureRecognizer(tap)
//    }
//    
//    func gestureRecognizer(gestureRecognizer: UIGestureRecognizer, shouldReceiveTouch touch: UITouch) -> Bool {
//        if touch.view!.isKindOfClass(UIDevFormTableView) {
//            return true
//        }
//        return false
//    }
//    
//    func onFormTableViewTouch() {
//        self.endEditing(true)
//    }
    
    private var tableViewTop:CGFloat?
    
    private var notification:NSNotification?
    
    func onKeyBoardWillHide(notification:NSNotification) {
        self.notification = nil
        var time:NSTimeInterval = 0.25
        if let userInfo:NSDictionary = notification.userInfo {
            if let duration:NSTimeInterval = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as? NSTimeInterval {
                time = duration
            }
        }
        if let top:CGFloat = self.tableViewTop {
            UIView.animateWithDuration(time) {
                self.frame.origin.y = top
            }
        }
    }
    
    func onKeyBoardWillShow(notification:NSNotification) {
        self.notification = notification
        if self.tableViewTop == nil {
            self.tableViewTop = self.frame.origin.y
        }
        
        if let userInfo:NSDictionary = notification.userInfo {
            if let keyboardRect:CGRect = userInfo.objectForKey(UIKeyboardFrameEndUserInfoKey)?.CGRectValue {
                if let cell:UIDevFormTableViewCell = self.currentSelectedCell {
                    var nextCell:UIDevFormTableViewCell = cell
                    if let indexPath = self.indexPathForCell(cell) {
                        var nextIndex:NSIndexPath = indexPath
                        var t_nextIndexPath:NSIndexPath?
                        if indexPath.row + 1 < self.sections[indexPath.section].fields.count {
                            t_nextIndexPath = NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)
                        } else {
                            if indexPath.section + 1 < self.sections.count {
                                t_nextIndexPath = NSIndexPath(forRow: 0, inSection: indexPath.section + 1)
                            }
                        }
                        if let nextIndexPath = t_nextIndexPath {
                            if let next:UIDevFormTableViewCell = self.cellForRowAtIndexPath(nextIndexPath) as? UIDevFormTableViewCell {
                                nextCell = next
                                nextIndex = nextIndexPath
                            }
                        }
                        let rectInTableView = self.rectForRowAtIndexPath(nextIndex)
                        let rect = nextCell.convertRect(rectInTableView, toView: self.superview)
                        let yToScreen = rect.origin.y - rectInTableView.origin.y + self.superview!.frame.origin.y
                        if let field:DevFormField = nextCell.field {
                            if field.height + yToScreen > keyboardRect.origin.y {
                                let top:CGFloat = keyboardRect.origin.y - (field.height + yToScreen) + self.frame.origin.y
                                var time:NSTimeInterval = 0.25
                                if let duration:NSTimeInterval = userInfo.objectForKey(UIKeyboardAnimationDurationUserInfoKey) as? NSTimeInterval {
                                    time = duration
                                }
                                UIView.animateWithDuration(time) {
                                    self.frame.origin.y = top
                                }
                            }
                        }
                        
                    }
                }
            }
        }
    }
    
    private var currentSelectedCell:UIDevFormTableViewCell?
    
    func setCurrentSelectedCell(cell:UIDevFormTableViewCell) {
        self.currentSelectedCell = cell
        if let notification = self.notification {
            self.onKeyBoardWillShow(notification)
        }
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let row:DevFormField = self.sections[indexPath.section].fields[indexPath.row]
        if let cell:UIDevFormTableViewCell = tableView.dequeueReusableCellWithIdentifier("UIDevFormTableViewCellIdentifier", forIndexPath: indexPath) as? UIDevFormTableViewCell {
            row.addToFormTableViewCell(self, cell: cell)
            row.onInitTableViewCell(self, row, cell)
            return cell
        }
        return UITableViewCell()
    }
    
    func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        cell.separatorInset = tableView.separatorInset
        if #available(iOS 8.0, *) {
            cell.layoutMargins = UIEdgeInsetsZero
        }
    }
    
    func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
       
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return self.sections[section].getDevFormSectionView(self)
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return self.sections[section].height
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        if section == self.sections.count - 1 {
            return self.lastFootHeight
        }
        return 0.01
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return self.sections[indexPath.section].fields[indexPath.row].height
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return self.sections.count
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return sections[section].fields.count
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let field = self.sections[indexPath.section].fields[indexPath.row]
        tableView.deselectRowAtIndexPath(indexPath, animated: field.isAnimated())
        field.click()
    }
    
    func tableView(tableView: UITableView, shouldHighlightRowAtIndexPath indexPath: NSIndexPath) -> Bool {
        let animated = self.sections[indexPath.section].fields[indexPath.row].isAnimated()
        if !animated {
            tableView.endEditing(true)
        }
        return animated
    }
    
    func getFormValues() -> [String:AnyObject] {
        var values:[String:AnyObject] = [:]
        for var i=0; i<self.sections.count; i++ {
            let fields:[DevFormField] = self.sections[i].fields
            for var j=0; j<fields.count; j++ {
                let field:DevFormField = fields[j]
                if let value:AnyObject = field.getFieldValue() {
                    if let l_value:AnyObject = values[field.name] {
                        if let valueArray:[AnyObject] = l_value as? [AnyObject] {
                            var t_values:[AnyObject] = valueArray
                            t_values.append(value)
                        } else {
                            var t_values:[AnyObject] = []
                            t_values.append(l_value)
                            t_values.append(value)
                            values[field.name] = t_values
                        }
                    } else {
                        values[field.name] = value
                    }
                }
            }
        }
        return values
    }
    
    func setFormValue(name:String, value:AnyObject?) {
        for var i=0; i<self.sections.count; i++ {
            let fields:[DevFormField] = self.sections[i].fields
            for var j=0; j<fields.count; j++ {
                let field:DevFormField = fields[j]
                if name == field.name {
                    field.setFieldValue(value)
                }
            }
        }
    }
    
    func setFormValues(values:[String:AnyObject]) {
        for item:(key:String, value:AnyObject) in values {
            self.setFormValue(item.key, value: item.value)
//            self.setFormValue(key, value: value)
        }
    }
    
    private func nextEditableView(editableView: UIView) -> [String:NSObject] {
        var viewIndexed:Bool = false
        var result:[String:NSObject] = [:]
        for var i=0; i<self.sections.count; i++ {
            for var j=0; j<self.sections[i].fields.count; j++ {
                let row = self.sections[i].fields[j].getEditableView()
                if viewIndexed {
                    result["nextSection"] = i
                    result["nextRow"] = j
                    result["view"] = row
                    return result
                } else {
                    if let view = row {
                        if view == editableView {
                            viewIndexed = true
                            result["section"] = i
                            result["row"] = j
                        }
                    }
                }
            }
        }
        return result
    }
    
    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.endEditing(true)
        var result:[String:NSObject] = self.nextEditableView(textField)
        if textField.returnKeyType == UIReturnKeyType.Next {
            if let next:UIView = result["view"] as? UIView {
                if next.canBecomeFirstResponder() {
                    next.becomeFirstResponder()
                }
            }
        }
        if let section = result["section"] as? Int {
            if let row = result["row"] as? Int {
                let field:DevFormField = self.sections[section].fields[row]
                self.onReturnKeyClick(self, field, textField.returnKeyType)
            }
        }
        return true
    }
    
}
